package validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class PersonValidator implements Validator {
    //给谁校验
    @Override
    public boolean supports(Class<?> clazz) {
        return Person.class.equals(clazz);
    }

    //校验规则
    @Override
    public void validate(Object target, Errors errors) {
        //name不为空
        ValidationUtils.rejectIfEmpty(errors, "name",
                "name.empty", "name is null");

        //age不小于0,不能大于200
        Person p = (Person) target;
        if (p.getAge() < 0 || p.getAge() > 200) {
            errors.rejectValue("age", "age.value.error", "name is wrong");
        }
    }
}
